# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

from contextlib import contextmanager
import pdb
import sys

from expect_tests.type_definitions import Handler

# "no __init__ method" pylint: disable=W0232


class DebugHandler(Handler):
  SKIP_RUNLOOP = False

  @staticmethod
  @contextmanager
  def run_stage_loop_ctx(test):
    dbg = pdb.Pdb()

    for path, line, funcname in test.breakpoints:
      dbg.set_break(path, line, funcname=funcname)
      dbg.reset()

      def dispatch_thunk(*args):
        """Allows us to continue until the actual breakpoint."""
        val = dbg.trace_dispatch(*args)
        dbg.set_continue()
        sys.settrace(dbg.trace_dispatch)
        return val

      sys.settrace(dispatch_thunk)
      try:
        yield
      except pdb.bdb.BdbQuit:
        pass
      dbg.quitting = 1
      sys.settrace(None)


